"use client";
import React, { useEffect, useRef } from "react";
import { Chart } from "@antv/g2";

const CookieChart: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null); // 绑定到 div

  useEffect(() => {
    if (!chartRef.current) return; // 确保 div 存在

    const chart = new Chart({
      container: chartRef.current, // 绑定 div
      autoFit: true,
    });

    const data = [
      { item: "事例一", count: 40, percent: 0.4 },
      { item: "事例二", count: 21, percent: 0.21 },
      { item: "事例三", count: 17, percent: 0.17 },
      { item: "事例四", count: 13, percent: 0.13 },
      { item: "事例五", count: 9, percent: 0.09 },
    ];

    chart.coordinate({ type: "theta", outerRadius: 0.8, innerRadius: 0.5 });

    chart
      .interval()
      .data(data)
      .transform({ type: "stackY" })
      .encode("y", "percent")
      .encode("color", "item")
      .legend("color", { position: "bottom", layout: { justifyContent: "center" } })
      .label({
        position: "outside",
        text: (data) => `${data.item}: ${data.percent * 100}%`,
      })
      .tooltip((data) => ({
        name: data.item,
        value: `${data.percent * 100}%`,
      }));

    chart
      .text()
      .style("text", "主机")
      .style("x", "50%")
      .style("y", "50%")
      .style("dy", -25)
      .style("fontSize", 34)
      .style("fill", "#8c8c8c")
      .style("textAlign", "center");

    chart
      .text()
      .style("text", "200")
      .style("x", "50%")
      .style("y", "50%")
      .style("dx", -25)
      .style("dy", 25)
      .style("fontSize", 44)
      .style("fill", "#8c8c8c")
      .style("textAlign", "center");

    chart
      .text()
      .style("text", "台")
      .style("x", "50%")
      .style("y", "50%")
      .style("dx", 35)
      .style("dy", 25)
      .style("fontSize", 34)
      .style("fill", "#8c8c8c")
      .style("textAlign", "center");

    chart.render();

    return () => {
      chart.destroy(); // ✅ 组件卸载时清理图表，避免内存泄漏
    };
  }, []);

  return <div ref={chartRef} style={{ width: "100%", height: "100%" }} />; // 让图表占满 div
};

export default CookieChart;
